﻿using System;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;

namespace FileManager_Client.Utility
{
    public static class CryptographyGlobal
    {
        public static string Encode(string encryptString)
        {
            if (string.IsNullOrEmpty(encryptString)) return "";
            return Cryptographer.EncryptSymmetric(GlobalString.System_Config_String.ConfigDpapiCryptName, encryptString);
        }
        public static string Decode(string decryptString)
        {
            if (string.IsNullOrEmpty(decryptString)) return "";
            var result = string.Empty;
            try
            {
                result = Cryptographer.DecryptSymmetric(GlobalString.System_Config_String.ConfigDpapiCryptName, decryptString);
            }
            catch (Exception)
            {
                return decryptString;
            }
            return result;
        }

        public static string CreateHash(string plaintString)
        {
            return Cryptographer.CreateHash(GlobalString.System_Config_String.ConfigMd5TypeName, plaintString);
        }
        public static bool CompareHash(string plaintString, string hashedString)
        {
            return Cryptographer.CompareHash(GlobalString.System_Config_String.ConfigMd5TypeName, plaintString, hashedString);
        }

        public static string Md5Encrypt(string strText)
        {
            //var cl = strText;
            //var pwd = "";
            //var md5 = MD5.Create();//实例化一个md5对像
            //// 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            //byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            //// 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            //for (var i = 0; i < s.Length; i++)
            //{
            //    // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符
            //    pwd = pwd + s[i].ToString("X");

            //}
            //return pwd;

            var md5 = new MD5CryptoServiceProvider();
            var encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(strText));
            var sb = new StringBuilder();
            foreach (var t in encryptedBytes)
                sb.AppendFormat("{0:x2}", t);
            return sb.ToString().ToUpper();
            //return FormsAuthentication.HashPasswordForStoringInConfigFile(strText,
            //                                                              GlobalString.System_Config_String.EncodeMd5Key);
        }
    }
}